<script setup lang="ts">
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons-vue'
import { delayTimer } from '@v-c/utils'
import { AxiosError } from 'axios'
import SlideVerify from 'vue3-slide-verify'
import { nextTick, ref } from 'vue'
import GlobalLayoutFooter from '~/layouts/components/global-footer/index.vue'
import { loginApi, registerApi } from '~/api/common/login'
import { getQueryParam } from '~/utils/tools'
import type { LoginMobileParams, LoginParams, RegisterParams } from '~@/api/common/login'
import pageBubble from '@/utils/page-bubble'
import 'vue3-slide-verify/dist/style.css'

const { t } = useI18nLocale()
const message = useMessage()
const notification = useNotification()
const appStore = useAppStore()
const { layoutSetting } = storeToRefs(appStore)
const router = useRouter()
const token = useAuthorization()
// 新增滑块验证相关状态
const showVerify = ref(false)
const verifySuccess = ref(false)
// 状态管理
const isRegister = ref(false)

const loginModel = reactive({
  username: undefined,
  password: undefined,
  mobile: undefined,
  code: undefined,
  type: 'account',
  remember: true,
})

const registerModel = reactive({
  username: undefined,
  password: undefined,
  confirmPassword: undefined,
  mobile: undefined,
  code: undefined,
  type: 'email',
})

// 新增图片预加载逻辑
async function preloadImages(urls: string[]) {
  await Promise.all(
    urls.map(url =>
      new Promise((resolve) => {
        const img = new Image()
        img.src = url
        img.onload = resolve
        img.onerror = resolve
      }),
    ),
  )
}

// 修改滑块验证组件使用方式
const slideVerifyKey = ref(0)
const localImages = ref([
  '/images/1.jpg',
  '/images/2.jpg',
  '/images/3.jpg',
  '/images/4.jpg',
  '/images/5.jpg',
  '/images/6.jpg',
])

// 初始化时预加载图片
onMounted(async () => {
  await preloadImages(localImages.value)
  slideVerifyKey.value++ // 强制重新渲染组件
})

// 添加重试按钮
async function refreshVerify() {
  slideVerifyKey.value++
  await nextTick()
  await preloadImages(localImages.value)
}

// 滑块验证成功回调
function handleVerifySuccess() {
  verifySuccess.value = true
  showVerify.value = false
  submit() // 触发实际提交
}

// 滑块验证失败回调
function handleVerifyFail() {
  message.error(t('verify.failed'))
  verifySuccess.value = false
}

const formRef = shallowRef()
const registerFormRef = shallowRef()
const codeLoading = shallowRef(false)
const resetCounter = 60
const submitLoading = shallowRef(false)
const errorAlert = shallowRef(false)
const bubbleCanvas = ref<HTMLCanvasElement>()
const { counter, pause, reset, resume, isActive } = useInterval(1000, {
  controls: true,
  immediate: false,
  callback(count) {
    if (count) {
      if (count === resetCounter)
        pause()
    }
  },
})
async function getCode() {
  codeLoading.value = true
  try {
    const validateModel = isRegister.value ? registerModel : loginModel
    await (isRegister.value ? registerFormRef : formRef).value.validate(['mobile'])
    setTimeout(() => {
      reset()
      resume()
      codeLoading.value = false
      message.success('验证码是：123456')
    }, 3000)
  }
  catch (error) {
    codeLoading.value = false
  }
}

// 密码验证规则
async function validatePasswordConfirm(_: any, value: string) {
  if (value !== registerModel.password) {
    return Promise.reject(t('pages.register.confirmPasswordMismatch'))
  }
  return Promise.resolve()
}

async function submit() {
  if (!verifySuccess.value) {
    showVerify.value = true
    return
  }

  const isRegisterMode = isRegister.value
  const form = isRegisterMode ? registerFormRef.value : formRef.value
  submitLoading.value = true

  try {
    await form.validate()
    let params: LoginParams | LoginMobileParams | RegisterParams

    if (isRegisterMode) {
      params = {
        username: registerModel.username,
        password: registerModel.password,
        mobile: registerModel.mobile,
        code: registerModel.code,
      }
    }
    else if (loginModel.type === 'account') {
      params = {
        username: loginModel.username,
        password: loginModel.password,
      }
    }
    else {
      params = {
        mobile: loginModel.mobile,
        code: loginModel.code,
        type: 'mobile',
      }
    }

    const { data } = isRegisterMode
      ? await registerApi(params as RegisterParams)
      : await loginApi(params)

    if (isRegisterMode) {
      message.success(t('pages.register.success'))
      isRegister.value = false
    }
    else {
      errorAlert.value = true
      token.value = data?.token
      notification.success({
        message: t('pages.login.success'),
        description: t('pages.login.welcomeBack'),
        duration: 3,
      })
      const redirect = getQueryParam('redirect', '/')
      router.push({ path: redirect, replace: true })
    }
  }
  catch (e) {
    if (e instanceof AxiosError) {
      errorAlert.value = true
      message.error(e.response?.data?.message || t('common.requestError'))
    }
  }
  finally {
    submitLoading.value = false
    verifySuccess.value = false
    refreshVerify()
  }
}
onMounted(async () => {
  await delayTimer(300)
  pageBubble.init(unref(bubbleCanvas)!)
})

onBeforeUnmount(() => {
  pageBubble.removeListeners()
})
</script>

<template>
  <div class="login-container">
    <div h-screen w-screen absolute z-10>
      <canvas ref="bubbleCanvas" />
    </div>
    <div class="login-content flex-center">
      <div class="ant-pro-form-login-main rounded">
        <!-- 登录头部 -->
        <div
          class="flex-between h-15 px-4 mb-[2px]"
        >
          <div class="flex-end">
            <span class="ant-pro-form-login-logo">
              <img w-full h-full object-cover src="/logo.svg">
            </span>
            <span class="ant-pro-form-login-title">
              Cloud Album
            </span>
            <span class="ant-pro-form-login-desc">
              {{ t("pages.layouts.userLayout.title") }}
            </span>
          </div>
          <div class="login-lang flex-center relative z-11">
            <span
              class="flex-center cursor-pointer text-16px"
              @click="appStore.toggleTheme(layoutSetting.theme === 'dark' ? 'light' : 'dark')"
            >
              <!-- 亮色和暗黑模式切换按钮 -->
              <template v-if="layoutSetting.theme === 'light'">
                <carbon-moon />
              </template>
              <template v-else>
                <carbon-sun />
              </template>
            </span>
            <SelectLang />
          </div>
        </div>
        <a-divider m-0 />
        <!-- 登录主体 -->
        <div class="box-border flex min-h-[520px]">
          <!-- 登录框左侧 -->
          <div class="ant-pro-form-login-main-left min-h-[520px] flex-center  bg-[var(--bg-color-container)]">
            <img src="@/assets/images/login-left.png" class="h-5/6 w-5/6">
          </div>
          <a-divider m-0 type="vertical" class="ant-pro-login-divider  min-h-[520px]" />
          <!-- 登录框右侧 -->
          <div class="ant-pro-form-login-main-right px-5 w-[335px] flex-center flex-col relative z-11">
            <div class="text-center py-6 text-2xl">
              {{ t('pages.login.tips') }}
            </div>
            <template v-if="!isRegister">
              <a-form ref="formRef" :model="loginModel">
                <a-tabs v-model:active-key="loginModel.type" centered>
                  <a-tab-pane key="account" :tab="t('pages.login.accountLogin.tab')" />
                  <a-tab-pane key="mobile" :tab="t('pages.login.phoneLogin.tab')" disabled />
                </a-tabs>
                <!-- 判断是否存在error -->
                <a-alert
                  v-if="errorAlert && loginModel.type === 'account'" mb-24px
                  :message="t('pages.login.accountLogin.errorMessage')" type="error" show-icon
                />
                <a-alert
                  v-if="errorAlert && loginModel.type === 'mobile'" mb-24px
                  :message="t('pages.login.phoneLogin.errorMessage')" type="error" show-icon
                />
                <template v-if="loginModel.type === 'account'">
                  <a-form-item name="username" :rules="[{ required: true, message: t('pages.login.username.required') }]">
                    <a-input
                      v-model:value="loginModel.username" allow-clear
                      autocomplete="off"
                      :placeholder="t('pages.login.username.placeholder')" size="large" @press-enter="submit"
                    >
                      <template #prefix>
                        <UserOutlined />
                      </template>
                    </a-input>
                  </a-form-item>
                  <a-form-item name="password" :rules="[{ required: true, message: t('pages.login.password.required') }]">
                    <a-input-password
                      v-model:value="loginModel.password" allow-clear
                      :placeholder="t('pages.login.password.placeholder')" size="large" @press-enter="submit"
                    >
                      <template #prefix>
                        <LockOutlined />
                      </template>
                    </a-input-password>
                  </a-form-item>
                </template>
                <template v-if="loginModel.type === 'mobile'">
                  <a-form-item
                    name="mobile" :rules="[
                      { required: true, message: t('pages.login.phoneNumber.required') },
                      {
                        pattern: /^(86)?1([38][0-9]|4[579]|5[0-35-9]|6[6]|7[0135678]|9[89])[0-9]{8}$/,
                        message: t('pages.login.phoneNumber.invalid'),
                      },
                    ]"
                  >
                    <a-input
                      v-model:value="loginModel.mobile" allow-clear
                      :placeholder="t('pages.login.phoneNumber.placeholder')" size="large" @press-enter="submit"
                    >
                      <template #prefix>
                        <MobileOutlined />
                      </template>
                    </a-input>
                  </a-form-item>
                  <a-form-item name="code" :rules="[{ required: true, message: t('pages.login.captcha.required') }]">
                    <div flex items-center>
                      <a-input
                        v-model:value="loginModel.code"
                        style="flex: 1 1 0%; transition: width 0.3s ease 0s; margin-right: 8px;" allow-clear
                        :placeholder="t('pages.login.captcha.placeholder')" size="large" @press-enter="submit"
                      >
                        <template #prefix>
                          <LockOutlined />
                        </template>
                      </a-input>
                      <a-button :loading="codeLoading" :disabled="isActive" size="large" @click="getCode">
                        <template v-if="!isActive">
                          {{ t('pages.login.phoneLogin.getVerificationCode') }}
                        </template>
                        <template v-else>
                          {{ resetCounter - counter }} {{ t('pages.getCaptchaSecondText') }}
                        </template>
                      </a-button>
                    </div>
                  </a-form-item>
                </template>
                <div class="mb-24px flex-between">
                  <a-checkbox v-model:checked="loginModel.remember">
                    {{ t('pages.login.rememberMe') }}
                  </a-checkbox>
                  <a>{{ t('pages.login.forgotPassword') }}</a>
                </div>
                <a-button type="primary" block :loading="submitLoading" size="large" @click="submit">
                  {{ t('pages.login.submit') }}
                </a-button>
              </a-form>
            </template>
            <!-- 注册表单 -->
            <a-form v-else ref="registerFormRef" :model="registerModel">
              <a-tabs v-model:active-key="registerModel.type" centered>
                <a-tab-pane key="email" :tab="t('pages.register.title')" />
              </a-tabs>
              <a-form-item
                name="username"
                :rules="[{ required: true, message: t('pages.register.usernameRequired') }]"
              >
                <a-input
                  v-model:value="registerModel.username"
                  :placeholder="t('pages.register.usernamePlaceholder')"
                  size="large"
                >
                  <template #prefix>
                    <UserOutlined />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item
                name="password"
                :rules="[{ required: true, message: t('pages.register.passwordRequired') }]"
              >
                <a-input-password
                  v-model:value="registerModel.password"
                  :placeholder="t('pages.register.passwordPlaceholder')"
                  size="large"
                >
                  <template #prefix>
                    <LockOutlined />
                  </template>
                </a-input-password>
              </a-form-item>

              <a-form-item
                name="confirmPassword"
                :rules="[{ required: true, message: t('pages.register.confirmPasswordRequired') },
                         { validator: validatePasswordConfirm }]"
              >
                <a-input-password
                  v-model:value="registerModel.confirmPassword"
                  :placeholder="t('pages.register.confirmPasswordPlaceholder')"
                  size="large"
                >
                  <template #prefix>
                    <LockOutlined />
                  </template>
                </a-input-password>
              </a-form-item>

              <!-- <a-form-item
                name="mobile"
                :rules="loginModel.type === 'mobile' ? [
                  { required: true, message: t('pages.login.phoneNumber.required') },
                  { pattern: /^(86)?1([38][0-9]|4[579]|5[0-35-9]|6[6]|7[0135678]|9[89])[0-9]{8}$/,
                    message: t('pages.login.phoneNumber.invalid') },
                ] : []"
              >
                <a-input
                  v-model:value="registerModel.mobile"
                  :placeholder="t('pages.login.phoneNumber.placeholder')"
                  size="large"
                >
                  <template #prefix>
                    <MobileOutlined />
                  </template>
                </a-input>
              </a-form-item> -->

              <a-form-item
                name="code"
                :rules="[{ required: true, message: t('pages.login.captcha.required') }]"
              >
                <div flex items-center>
                  <a-input
                    v-model:value="registerModel.code"
                    style="flex: 1; margin-right: 8px;"
                    size="large"
                  >
                    <template #prefix>
                      <LockOutlined />
                    </template>
                  </a-input>
                  <a-button
                    :loading="codeLoading"
                    :disabled="isActive"
                    size="large"
                    @click="getCode"
                  >
                    {{ !isActive ? t('pages.login.phoneLogin.getVerificationCode')
                      : `${resetCounter - counter} ${t('pages.getCaptchaSecondText')}` }}
                  </a-button>
                </div>
              </a-form-item>

              <a-button
                type="primary"
                block
                :loading="submitLoading"
                size="large"
                @click="submit"
              >
                {{ isRegister ? t('pages.register.submit') : t('pages.login.submit') }}
              </a-button>
            </a-form>
            <!-- 滑块验证 -->
            <a-modal
              v-model:visible="showVerify"
              :footer="null"
              :width="400"
              :closable="false"
              centered
            >
              <SlideVerify
                :key="slideVerifyKey"
                :imgs="localImages"
                :slider-text="t('verify.slideText')"
                :accuracy="3"
                class="custom-slider"
                @success="handleVerifySuccess"
                @fail="handleVerifyFail"
              />
            </a-modal>
            <a-divider />
            <div class="mb-6 text-center">
              <a-button type="link" @click="isRegister = !isRegister">
                {{ isRegister ? t('pages.login.hasAccount') : t('pages.login.registerAccount') }}
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div py-24px px-50px fixed bottom-0 z-11 w-screen :data-theme="layoutSetting.theme" text-14px>
      <GlobalLayoutFooter
        :copyright="layoutSetting.copyright"
      >
        <template #renderFooterLinks>
          <footer-links />
        </template>
      </GlobalLayoutFooter>
    </div>
  </div>
</template>

<style lang="less" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: auto;
  background: var(--bg-color-container);
}

.login-lang {
  height: 40px;
  line-height: 44px;
}

.login-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.ant-pro-form-login-container {
  display: flex;
  flex: 1 1;
  flex-direction: column;
  height: 100%;
  padding: 32px 0;
  overflow: auto;
  background: inherit
}

.ant-pro-form-login-header a {
  text-decoration: none
}

.ant-pro-form-login-title {
  color: var(--text-color);
  font-weight: 600;
  font-size: 33px;
  line-height: 1;
}

.ant-pro-form-login-logo {
  width: 155px;
  height: 44px;
  margin-right: 16px;
  vertical-align: top
}

.ant-pro-form-login-desc {
  color: var(--text-color-1);
  font-size: 14px;
  margin-left: 16px
}

.ant-pro-form-login-main-right {
  .ant-tabs-nav-list {
    margin: 0 auto;
    font-size: 16px;
  }

  .ant-pro-form-login-other {
    line-height: 22px;
    text-align: center
  }

}

.ant-pro-form-login-main{
  box-shadow: var(--c-shadow);
}

.icon {
  margin-left: 8px;
  color: var(--text-color-2);
  font-size: 24px;
  vertical-align: middle;
  cursor: pointer;
  transition: color .3s;

  &:hover {
    color: var(--pro-ant-color-primary);
  }
}
.login-media(@width:100%) {
  .ant-pro-form-login-main{
    width: @width;
  }
  .ant-pro-form-login-main-left{
    display: none;
  }
  .ant-pro-form-login-main-right{
    width: 100%;
  }
  .ant-pro-form-login-desc{
    display: none;
  }
}
@media (min-width : 992px) {
  .ant-pro-form-login-main-left{
    width: 700px;
  }
}
@media(min-width:768px) and (max-width:991px){
  .ant-pro-login-divider{
    display: none;
  }
  .login-media(400px)
}
@media screen and (max-width:767px) {
  .login-media(350px);

  .ant-pro-login-divider{
    display: none;
  }
}

.custom-slider {
  --vs-primary-color: #1890ff; // 主题色
  --vs-slider-bg: #f0f2f5; // 背景色
  --vs-border-radius: 8px; // 圆角

  :deep(.vs-slider) {
    height: 40px !important;
    border-radius: 20px !important;
  }

  :deep(.vs-slider-button) {
    width: 50px !important;
    height: 38px !important;
    border-radius: 20px !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15) !important;

    &::after {
      content: '→';
      font-size: 18px;
      color: #1890ff;
    }
  }
}

.verify-footer {
  margin-top: 16px;
  text-align: center;
}

/* 添加加载动画 */
:deep(.vs-container) {
  position: relative;
  &::before {
    content: '图片加载中...';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1;
    color: #666;
  }
  &.vs-ready::before {
    display: none;
  }
}
</style>
